// app.js
const api = require('./utils/api')
App({
  globalData: {
    scale: 1,//屏幕比例
    navHeight: 0,
    tabHeight: 0,
    scanId: 0,
    webUrl:'',
    idLogin: false,
    openid: '',
    session_key: '',
    code: '',
    unionId: '',
    columnId: {
      banner: 1,//banner列表
      tabbar: 2,//底部标签
      find: 3,//找好玩
      theme: 4,//品牌馆
      chosen: 5, //浙里优选
      jsxl: 6,//及食行乐
      trip: 7,//智能伴旅
      grid: 8,//导航宫格
      scenery: 9,//风物志
      player: 10,//头号玩家
      find1: 11,//找好宿
      find2: 12,//找好吃
      find3: 13,//找好景
      find4: 14,//找好物
      find5: 25,//找好展
      myInfo: 15,//我的信息
      service1: 16,//交通服务
      service2: 17,//快速查询
      service3: 18,//热线服务
      service4: 19,//其他服务
      reserve: 20,//预约预定
      bulletin: 23,//公告栏
      hotNews: 24,//热门资讯
      addNews: 27//广告位
    }
  },

  onLaunch() {

    //全局字体适配
    wx.loadFontFace({
      global: true,
      family: '微软雅黑',
      source: 'https://big-file.oss-cn-hangzhou-zwynet-d01-a.internet.cloud.zj.gov.cn/font/MSYH.TTF',
      success: function () {
        //
      }
    })


    // 获取手机系统信息
    wx.getSystemInfo({
      success: res => {

        //导航高度
        this.globalData.navHeight = res.statusBarHeight + 46;
        //底部预留距离
        this.globalData.bottomHeight = res.screenHeight - res.safeArea.height - res.statusBarHeight;
        //首页滚动区高度
        this.globalData.scrollHeight = res.screenHeight - this.globalData.navHeight - this.globalData.bottomHeight - 47;
        //不同型号缩放比例
        this.globalData.scale = res.screenWidth * 2 / 375;
      }, fail(err) {
        console.log(err);
      }
    })
    // wx.checkSession({
    //   success: (res) => {
    //     //缓存未保存session_key，需要重新执行登录流程
    //     if (!wx.getStorageSync('login')) {
    //       this.getOpenId();
    //     }
    //   },
    //   fail: (e) => {
    //     //console.log(this);
    //     // session_key 已经失效，需要重新执行登录流程
    //     this.getOpenId();
    //   }
    // })
    //如果没有userId清除login缓存
    //if (!wx.getStorageSync('userId')) {
    //  wx.removeStorageSync('login');
    //}
    //用户访问次数记录
    api.setOutLink({
      "newsId": '0'
    }).then((res) => { })

    api.getIsLogin({}).then(res => {
      this.globalData.loginAdmin = res.data;
    })

    //判断userId是否乱码(5月份补丁)
    if (wx.getStorageSync('userId')) {
      let userId = wx.getStorageSync('userId');
      if (userId % 1 !== 0 || userId == 0) {
        let login = wx.getStorageSync('login');
        let userInfo = wx.getStorageSync('userInfo');
        api.setWxUserInfo({
          "openId": login.openid,
          "unionId": login.unionId,
          "mobile": login.phoneNumber,
          "nickName": userInfo.nickName,
          "avatarUrl": userInfo.avatarUrl,
          "gender": userInfo.gender,
          "country": userInfo.country,
          "province": userInfo.province,
          "city": userInfo.city,
          "language": userInfo.language
        }).then(res => {
          if (res.data.code != 0) {
            wx.removeStorageSync('login');
            wx.removeStorageSync('userInfo');
            wx.removeStorageSync('userId');
            return
          }
          wx.setStorageSync('userId', res.data.msg);
        })
      }

    }
  },

  //获取openID

  getOpenId() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: e => {
          //console.log(e);
          api.getOpenId({
            "JSCODE": e.code
          }).then((res) => {
            let login = {
              openid: res.data.openid,
              session_key: res.data.session_key,
              unionId: res.data.unionid
            }
            wx.setStorageSync('login', login);
            resolve(res);
          })
        }
      })
    })
  },


  //打开登录界面(不需要登录返回false)
  openLoginPage() {
    if (!this.globalData.idLogin) {
      this.globalData.idLogin = true;
      // if (!wx.getStorageSync('login')) {
      //   this.getOpenId();
      // }
      if (!this.globalData.loginAdmin) {
        this.globalData.idLogin = false;
        return false;
      } else if (wx.getStorageSync('userInfo')) {
        this.globalData.idLogin = false;
        return false;
      } else {
        this.jumpToUserLogin();
        return true;
      }
    } else {
      //重复点击
      return true;
    }

  },
  jumpToUserLogin() {
    wx.navigateTo({
      url: wx.getStorageSync('login').phoneNumber ? '/pages/loginInfo/loginInfo' : '/pages/login/login',
      success: () => {
        this.globalData.idLogin = false;
      }
    })
  },
  //点击打开导航
  onClickLocation(locationName, location) {
    if (location != "") {
      let plugin = requirePlugin('routePlan');
      let key = 'VFYBZ-DWHCD-5J546-HJ74A-KULH6-XZBLT';  //使用在腾讯位置服务申请的key
      let referer = '浙里好玩';   //调用插件的app的名称
      let endPoint = JSON.stringify({  //终点
        'name': locationName,
        'latitude': location.split(',')[1],
        'longitude': location.split(',')[0]
      });
      wx.navigateTo({
        url: 'plugin://routePlan/index?navigation=1&key=' + key + '&referer=' + referer + '&endPoint=' + endPoint
      });
    }
  },


  //通过cId筛选列表数据
  screenList(homeList, typeId) {
    let find = homeList.find(i => { return i.cId == typeId });
    if (!find) { return {} } else { return find }
  },

  //标签拆分函数
  spanSplit(list) {
    if (!list.cId) return;
    list.tabs = list.tabs.split(',');
    list.newsList.forEach((i, index) => {
      if (i.newsType) {
        list.newsList[index].newsType = i.newsType.split(',').splice(0, 3);
      }
    })
    return list;
  },

  //获取其他标签页面内容
  getInfoPage(page, type, nowPage, keyWord, byhot) {
    return new Promise((resolve, reject) => {
      if (wx.getStorageSync(type) && !nowPage && !keyWord) { resolve(wx.getStorageSync(type)) }
      api.getHomeInfo({
        "loadPage": page,
        "nowPage": nowPage,
        "keyWord": keyWord,
        "byhot": byhot
      }).then((res) => {
        if (res.data.code === '1') return reject();
        if (!nowPage && !keyWord) { wx.setStorageSync(type, res.data.data) };
        resolve(res.data.data);
      })
    })
  },

  //跳转链接
  toOutLink(e) {
    let url = e.currentTarget.dataset.url;
    //判断是否为空
    if (!url) return;

    //跳转小程序
    if (url.indexOf("|appid|") != -1) {
      this.toApp(url.substring(0, url.indexOf("|appid|")), url.substring(url.indexOf("|appid|") + 7));
      return;
    }

    //判断内外部链接以及拨打电话
    if (url.indexOf("tel:") != -1) {
      wx.makePhoneCall({
        phoneNumber: url.split(":")[1]
      })
    } else if (url.substring(0, 5) != 'https') {

      let type = url.substring(url.lastIndexOf('\/') + 1, url.length);
      let typeList = ['myInfo', 'index', 'reserve', 'service']


      //内部跳转
      if (typeList.some((i, index) => { return i == type })) {
        wx.switchTab({
          url: url
        });
      } else {
        wx.navigateTo({
          url: url
        })
      }
    } else {

      //console.log(wx.getStorageSync('login').phoneNumber);

      //判断是否为空
      if (!e.currentTarget.dataset.url) return;
      //跳转外链统计用
      if (e.currentTarget.dataset.newsId) {
        api.setOutLink({
          "newsId": e.currentTarget.dataset.newsId
        }).then((res) => { })
      }

      //外部跳转
      let openid = e.currentTarget.dataset.url.indexOf('?') != -1 ? '&openid=' : '?openid=';
      if (this.globalData.loginAdmin) {
        url = e.currentTarget.dataset.url + openid + this.getRandomAlphaNum(8) + wx.getStorageSync('userId') + this.getRandomAlphaNum(8);
      } else {
        url = e.currentTarget.dataset.url + openid + '0';
      }
      
      wx.navigateTo({
        url: '/pages/web/web',
        success: function (res) {
          res.eventChannel.emit('acceptDataFromOpenerPage', { url: url })
        }
      })
    }
  },



  //跳转小程序
  toApp(appId, path) {
    wx.navigateToMiniProgram({
      appId: appId,
      path: path
    })
  },

  //生成字母加数字的随机数
  getRandomAlphaNum(len){
    var rdmString = "";
    for (; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
    return rdmString.substr(0, len);
  }
})
